import AddOrderProductCard from '@/components/AddOrderProductCard';
import OrderDetailModal from '@/components/OrderDetailModal';
import { getRestaurantAreas, getRestaurantTables } from '@/services/ant-design-pro/desk';
import { getProductCategory, getProductList } from '@/services/ant-design-pro/product';
import { createTrade, previewTradePrice, printTradeTicket } from '@/services/order';
import { PageContainer } from '@ant-design/pro-components';
import {
  AutoComplete,
  Button,
  Card,
  Col,
  Divider,
  Empty,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Row,
  Select,
  Switch,
  Tabs,
  Tag,
} from 'antd';
import React, { useEffect, useState } from 'react';

const { Option } = Select;

enum DeskStatus {
  Free = '空闲',
  Occupied = '就餐中',
}

const data = [
  {
    key: '1',
    name: 'Craft Beer A',
    sku: '大杯',
    price: '￥50',
    quantity: 1,
  },
  {
    key: '2',
    name: 'Craft Beer B',
    sku: '小杯',
    price: '￥60',
    quantity: 1,
  },
  {
    key: '3',
    name: 'Craft Beer C',
    sku: '大杯',
    price: '￥70',
    quantity: 1,
  },
];

const DeskList: React.FC = () => {
  const [checkoutModalOpen, setCheckoutModalOpen] = useState(false);
  const [deskDetailOpen, setDeskDetailOpen] = useState(false);
  const [orderProductOpen, setOrderProductOpen] = useState(false);

  const [deskDetail, setDeskDetail] = useState(null);
  const [selectedItems, setSelectedItems] = useState([]);
  const [tableList, setTableList] = useState([]);
  const [tableAreaList, setTableAreaList] = useState([]);
  const [areaList, setAreaList] = useState([]);
  const [productList, setProductList] = useState([]);
  const [productCollection, setProductCollection] = useState([]);
  const [productDetail, setProductDetail] = useState(null);
  const [orderParams, setOrderParams] = useState({});
  const [tradeOrderItem, setTradeOrderItem] = useState({});
  const [orderDiscountPreview, setOrderDiscountPreview] = useState({});
  const [currentOrderId, setCurrentOrderId] = useState(null);

  const orderForm = Form.useForm()[0];

  const desks = [
    { id: 1, name: '1号桌', status: DeskStatus.Occupied, money: 100 },
    { id: 2, name: '2号桌', status: DeskStatus.Free, money: 0 },
    { id: 3, name: '3号桌', status: DeskStatus.Occupied, money: 200 },
    { id: 4, name: '4号桌', status: DeskStatus.Free, money: 0 },
    { id: 5, name: '5号桌', status: DeskStatus.Occupied, money: 300 },
    { id: 6, name: '6号桌', status: DeskStatus.Free, money: 0 },
  ];

  const getStatusTag = (status: DeskStatus) => {
    switch (status) {
      case DeskStatus.Free:
        return <Tag color="green">{status}</Tag>;
      case DeskStatus.Occupied:
        return <Tag color="red">{status}</Tag>;
      default:
        return null;
    }
  };

  const handleDesk = (data) => {
    setDeskDetailOpen(true);
    setDeskDetail(data);
  };

  const handleQuantityChange = (key, value) => {
    setSelectedItems((prevItems) =>
      prevItems.map((item) => (item.key === key ? { ...item, quantity: value } : item)),
    );
  };

  const handleAddItem = (item) => {
    setSelectedItems((prevItems) => {
      const existingItem = prevItems.find((i) => i.key === item.key && i.sku === item.sku);
      if (existingItem) {
        return prevItems.map((i) =>
          i.key === item.key && i.sku === item.sku
            ? { ...i, quantity: i.quantity + item.quantity }
            : i,
        );
      } else {
        return [...prevItems, item];
      }
    });
  };

  const ProductColumns = [
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      key: 'sku',
      render: (_, record) => (
        <Select
          defaultValue={record.sku}
          style={{ width: 120 }}
          onChange={(value) => (record.sku = value)}
        >
          <Option value="大杯">大杯</Option>
          <Option value="小杯">小杯</Option>
        </Select>
      ),
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      render: (_, record) => (
        <InputNumber
          size="large"
          min={1}
          defaultValue={1}
          onChange={(value) => (record.quantity = value)}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button type="primary" onClick={() => handleAddItem(record)}>
          添加
        </Button>
      ),
    },
  ];

  const ProductShowColumns = [
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      key: 'sku',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
    },
  ];

  const initTable = async (areaId = undefined) => {
    const resp = await getRestaurantTables({ areaId, page: 1, pageSize: 50 });

    const { list } = resp?.data;

    const listByArea = [];
    list.forEach((item) => {
      const areaIndex = listByArea.findIndex((_) => _?.area === item.area);
      console.log('[areaIndex]', areaIndex);
      if (areaIndex === -1) {
        listByArea.push({
          area: item.area,
          tables: [item],
        });
      } else {
        listByArea[areaIndex].tables.push(item);
      }
    });
    console.log('[listByArea]', listByArea);
    setTableAreaList(listByArea);
    setTableList(list);
  };

  const initArea = async () => {
    const resp = await getRestaurantAreas({ page: 1, pageSize: 50 });

    const { list } = resp?.data;

    setAreaList(list);
  };

  const initProductList = async (params = {}) => {
    const resp = await getProductList({ ...params, status: 1, page: 1, pageSize: 50 });

    const { list } = resp?.data;

    setProductList(list);
  };

  const handleTabClick = (tab) => {
    if (tab === 'all') {
      initTable();
    } else {
      initTable(tab);
    }
  };

  const handleOrder = (tableId) => {
    setOrderProductOpen(true);
    setOrderParams({
      channel: 'minipro',
      restaurantId: window.MERCHANT_ID,
      tableId,
    });
  };

  const initProductCollection = async () => {
    const resp = await getProductCategory({ page: 1, pageSize: 50 });
    const { list } = resp?.data;
    setProductCollection(list);
  };

  const handleCreateTrade = async () => {
    orderForm.validateFields().then(async () => {
      const resp = await createTrade(orderParams);
      if (resp?.code === 0) {
        message.success('创建成功');
        setOrderParams({});
        setOrderProductOpen(false);
        const orderId = resp?.data?.id;
        console.log('[resp?.data]', resp?.data);
        Modal.confirm({
          title: '是否需要打印制作小票',
          onOk: async () => {
            console.log('打印小票');
            const resp = await printTradeTicket(orderId);
            if (resp.code === 0) {
              message.success('操作成功');
            }
          },
        });

        initTable();
      }
    });
  };

  const handleProductPreviewPrice = async (tradeOrderList) => {
    const resp = await previewTradePrice({ ...orderParams, tradeOrderList });
    console.log('[resp]', resp);
    setOrderDiscountPreview(resp?.data);
  };

  useEffect(() => {
    initArea();
    initTable();
    initProductList();
    initProductCollection();
  }, []);
  return (
    <>
      <Modal
        zIndex={9995}
        width={'102vw'}
        title="点单"
        destroyOnClose
        open={orderProductOpen}
        onCancel={() => setOrderProductOpen(false)}
        onOk={() => {
          handleCreateTrade();
          orderForm.resetFields();
        }}
        centered
      >
        <Card title="基础信息">
          <Form
            form={orderForm}
            onValuesChange={(changedValues, allValues) =>
              setOrderParams({ ...orderParams, ...allValues })
            }
            labelCol={{
              span: '2',
            }}
          >
            <Form.Item label="人数" name="seats">
              <InputNumber></InputNumber>
            </Form.Item>

            <Form.Item label="备注" name={'remark'}>
              <Input.TextArea></Input.TextArea>
            </Form.Item>
          </Form>
        </Card>

        <AddOrderProductCard
          onChange={
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            (tradeOrderList) => {
              console.log('[tradeOrderList]', tradeOrderList);
              setOrderParams({
                ...orderParams,
                tradeOrderList,
              });
            }
          }
        ></AddOrderProductCard>

        {/* <Card className={'mt20'} title="商品列表">
          <Flex gap={20}>
            <Input
              placeholder="输入名称搜索"
              style={{ width: '200px' }}
              onChange={(val) => {
                initProductList({
                  keyword: val.target.value,
                });
              }}
            ></Input>
            <Select
              placeholder="选择商品分类"
              style={{ width: '200px' }}
              allowClear
              onChange={(val) => {
                console.log('[val]', val);
              }}
            >
              {productCollection.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Flex>

          <Row className={'mt20'} gutter={[10, 10]}>
            {productList.length > 0 &&
              productList.map((item) => (
                <Col span={3} key={item.id}>
                  <Card
                    className="h100"
                    style={{ cursor: 'pointer' }}
                    onClick={() => {
                      initProductDetail(item.id);
                    }}
                  >
                    <div
                      className={'flex-center'}
                      style={{
                        height: '60px',
                        width: 'auto',
                        objectFit: 'cover',
                        overflow: 'hidden',
                      }}
                    >
                      {item.image ? (
                        <img
                          className={'w100 h100'}
                          src={item.image}
                          alt=""
                          style={{ objectFit: 'contain' }}
                        />
                      ) : (
                        <div>暂无图片</div>
                      )}
                    </div>
                    <div className={'mt10 text-center bold'}>{item.title}</div>
                  </Card>
                </Col>
              ))}
          </Row>
        </Card>

        <Card
          title="已选商品"
          className="mt20"
          extra={
            orderParams?.tradeOrderList?.length > 0 && (
              <div className="bold">
                <div>折扣金额：{orderDiscountPreview?.discountAmount}</div>
                <div>总价：{orderDiscountPreview?.totalAmount}</div>
              </div>
            )
          }
        >
          {orderParams?.tradeOrderList?.length === 0 ||
            (!orderParams?.tradeOrderList && (
              <Empty description="暂无商品" image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>
            ))}
          {orderParams?.tradeOrderList?.length > 0 && (
            <>
              <Row justify="space-between" className="w100" style={{ fontWeight: 'bold' }}>
                <Col span={4}>商品名称</Col>
                <Col span={4}>SKU</Col>
                <Col span={4}>价格</Col>
                <Col span={4}>数量</Col>
              </Row>
              {orderParams?.tradeOrderList?.map((item) => (
                <Row key={item.key} justify="space-between" className="mt10">
                  <Col span={4}>{item.product.title}</Col>
                  <Col span={4}>
                    {
                      item.product.variants.find(
                        (variant: { id: any; price: any }) => variant.id === item.variantId,
                      )?.attributeValues?.[0]?.value
                    }
                  </Col>
                  <Col span={4}>{item.product.price}</Col>
                  <Col span={4}> {item.quantity}</Col>
                </Row>
              ))}
            </>
          )}
        </Card> */}
      </Modal>

      <Modal
        title="结账"
        open={checkoutModalOpen}
        onCancel={() => {
          setCheckoutModalOpen(false);
        }}
        className="w100"
        zIndex={101}
      >
        <Card title="会员信息">
          <AutoComplete placeholder="请输入会员手机号搜索" className="w100"></AutoComplete>
          <Row className="mt20">
            <Col span={24}>
              <Row justify="space-between">
                <Col>余额：</Col>
                <Col>￥180</Col>
              </Row>
              <Row justify="space-between" className="mt10">
                <Col>积分</Col>
                <Col>2000</Col>
              </Row>
            </Col>
          </Row>
        </Card>

        <Card title="订单折扣" className="mt20">
          <Form layout="vertical">
            <Form.Item label="使用会员积分抵扣">
              <Switch></Switch>
            </Form.Item>
            <Form.Item label="使用会员余额抵扣">
              <Switch defaultChecked={true}></Switch>
            </Form.Item>
          </Form>
        </Card>

        <Row className="mt20">
          <Col span={24}>
            <Row justify="space-between">
              <Col>折扣列表：</Col>
            </Row>
            <Row justify="space-between">
              <Col>整单折扣:</Col>
              <Col>9折</Col>
            </Row>
            <Row justify="space-between">
              <Col>折扣金额：</Col>
              <Col>-￥180</Col>
            </Row>

            <Divider></Divider>

            <Row justify="space-between">
              <Col>总计金额：</Col>
              <Col>￥180</Col>
            </Row>
          </Col>
        </Row>
      </Modal>

      <OrderDetailModal
        orderId={currentOrderId}
        onCancel={() => {
          setCurrentOrderId(null);
          initTable();
        }}
      ></OrderDetailModal>

      <PageContainer style={{ width: '100vw' }}>
        <Tabs onTabClick={handleTabClick} type="card" size="large" className="w100">
          <Tabs.TabPane key={'all'} tab={'全部'}>
            <div className="flex-col w100">
              {tableAreaList.map((tableArea) => {
                return (
                  <div key={tableArea.area} className="w100 mb10">
                    <h3 className="bold">区域：{tableArea.area}</h3>
                    <Row gutter={[10, 10]}>
                      {tableArea?.tables?.map((desk) => {
                        return (
                          <Col span={6} key={desk.id}>
                            <Card
                              key={desk.id}
                              title={desk.name}
                              hoverable
                              onClick={(e) => {
                                if (desk?.processingTrade) {
                                  e.stopPropagation();
                                  setCurrentOrderId(desk?.processingTrade);
                                } else {
                                  e.stopPropagation();
                                  handleOrder(desk.id);
                                }
                              }}
                            >
                              {desk?.processingTrade && (
                                <h3 className="bold text-center red">有未完结订单</h3>
                              )}

                              {!desk?.processingTrade && (
                                <h3 className="bold text-center ">空闲</h3>
                              )}
                            </Card>
                          </Col>
                        );
                      })}
                    </Row>
                  </div>
                );
              })}
            </div>
          </Tabs.TabPane>
          {areaList.map((item) => {
            return (
              <Tabs.TabPane key={item.id} tab={item.name}>
                <Row gutter={[10, 10]}>
                  {tableList.map((desk) => (
                    <Col span={6} key={desk.id}>
                      <Card
                        key={desk.id}
                        title={desk.name}
                        hoverable
                        onClick={(e) => {
                          if (desk?.processingTrade) {
                            e.stopPropagation();
                            setCurrentOrderId(desk?.processingTrade);
                          } else {
                            e.stopPropagation();
                            handleOrder(desk.id);
                          }
                        }}
                        // extra={
                        //   <>
                        //     {desk?.processingTrade ? (
                        //       <Button
                        //         type="primary"
                        //         danger
                        //         size="small"
                        //         onClick={(e) => {
                        //           e.stopPropagation();
                        //           setCurrentOrderId(desk?.processingTrade);
                        //         }}
                        //       >
                        //         详情
                        //       </Button>
                        //     ) : (
                        //       <Button
                        //         type="primary"
                        //         size="small"
                        //         onClick={(e) => {
                        //           e.stopPropagation();
                        //           handleOrder(desk.id);
                        //         }}
                        //       >
                        //         点单
                        //       </Button>
                        //     )}
                        //   </>
                        // }
                      >
                        {desk?.processingTrade && (
                          <h3 className="bold text-center red">有未完结订单</h3>
                        )}

                        {!desk?.processingTrade && <h3 className="bold text-center ">空闲</h3>}
                      </Card>
                    </Col>
                  ))}
                </Row>
              </Tabs.TabPane>
            );
          })}
        </Tabs>

        {tableList?.length === 0 && <Empty></Empty>}
      </PageContainer>
    </>
  );
};

export default DeskList;
